//
//  TRFindListView.m
//  WeiMiLan
//
//  Created by anan on 14/11/22.
//  Copyright (c) 2014年 Mac. All rights reserved.
//

#import "TRTypeProductsListView.h"

@implementation TRTypeProductsListView{

}

- (id)initWithCoder:(NSCoder *)aDecoder
{
    self = [super initWithCoder:aDecoder];
    if (self) {
        self.currentArray = [[NSMutableArray alloc] init];
        self.alredaySelectArray = [[NSMutableDictionary alloc] init];

    }
    return self;
}

- (void)reload
{
    if (self.pullCollectionView==nil) {
        CHTCollectionViewWaterfallLayout *layout = [[CHTCollectionViewWaterfallLayout alloc] init];
       // layout.sectionInset = UIEdgeInsetsMake(10, 10, 10, 10);
//        layout.headerHeight = 0;
//        layout.footerHeight = 0;
//        layout.minimumColumnSpacing = 10;
//        layout.minimumInteritemSpacing = 10;
      
        layout.columnCount = 1;
        CGRect r = CGRectMake(0, 0, self.frame.size.width, self.frame.size.height);
        self.pullCollectionView=[[PullCollectionView alloc] initWithFrame:r collectionViewLayout:layout];
        self.pullCollectionView.delegate = self;
        self.pullCollectionView.pullDelegate = self;
        self.pullCollectionView.dataSource=self;
        self.pullCollectionView.allowsMultipleSelection = YES;
        self.pullCollectionView.pullBackgroundColor = [UIColor whiteColor];
        self.pullCollectionView.pullTextColor = [UIColor blackColor];
        [self.pullCollectionView registerNib:[UINib nibWithNibName:@"TRMemuCell" bundle:nil] forCellWithReuseIdentifier:@"TRMemuCell"];
        [self addSubview:self.pullCollectionView];
        self.pullCollectionView.autoresizingMask = UIViewAutoresizingFlexibleWidth|UIViewAutoresizingFlexibleHeight;
        self.pullCollectionView.backgroundColor = [UIColor whiteColor];
        [self loadAdlist];
        [self.pullCollectionView beginRefresh];
    }else{
        [self.pullCollectionView beginRefresh];
    }
}

#pragma mark - PullCollectionViewDelegate
-(void)pullCollectionViewDidTriggerRefresh:(PullCollectionView *)pullCollectionView{
    [self loadData:1];
}

- (void)pullCollectionViewDidTriggerLoadMore:(PullCollectionView*)pullCollectionView{
    [self loadData:self.nextPage];
}

- (void)loadData:(int)num
{
    NSMutableDictionary *dic = [[NSMutableDictionary alloc] init];
    [dic setObject:QLIntToNumber(num) forKey:@"PAGE_NUM"];
    [dic ql_setInterge:[self.info ql_intForKey:@"ID"] forKey:@"ID"];
    [dic setObject:ApplicationDelegate.currentUserId forKey:@"userId"];
    int c = [QLPropertyUtils getIntByKey:@"SEX_CATEGORY" defaultValue:-1];
    if (c>=0) {
        [dic ql_setInterge:c forKey:@"CATEGORY"];
    }
    NSString *bid = [QLPropertyUtils getStringByKey:@"BID" defaultValue:nil];
    if (bid) {
        [dic ql_setObject:bid forKey:@"BID"];
    }
    
    AFHTTPRequestOperationManager *requestManager = [AFHTTPRequestOperationManager manager];
    requestManager.responseSerializer.acceptableContentTypes = [NSSet setWithObject:@"text/html"];
    [requestManager GET:@"http://ping.vsmu.cn/app/Interface/Package?type=1010" parameters:dic success:^(AFHTTPRequestOperation *operation, id responseObject) {
        if ([responseObject[@"MESSAGE_INFO"][@"CODE"] isEqualToString:@"0000"]) {
            if (num==1) {
                //第一页
                if ([responseObject[@"PACKAGE_RSP"][@"PACKAGE"] isKindOfClass:[NSDictionary class]]) {
                    [self.currentArray addObject:responseObject[@"PACKAGE_RSP"][@"PACKAGE"]];
                }else{
                    self.currentArray = [NSMutableArray arrayWithArray:responseObject[@"PACKAGE_RSP"][@"PACKAGE"]];
                }
            }else{
                [self.currentArray addObjectsFromArray:responseObject[@"PACKAGE_RSP"][@"PACKAGE"]];
            }
            
//            //添加一个广告
//            if (num==1&&ApplicationDelegate.adArray) {
//                NSArray *arr = ApplicationDelegate.adArray;
//                int index = (int)self.tag;
//                if (index>=0&&index<arr.count) {
//                    NSDictionary *dic = [arr objectAtIndex:index];
//                    [self.currentArray insertObject:dic atIndex:0];
//                }
//              
//            }
            
            NSDictionary *pageInfo = responseObject[@"PAGE_INFO"];
            self.nextPage = [pageInfo ql_intForKey:@"NEXT"];
            self.currentPage = [pageInfo ql_intForKey:@"NUMBER"];
            if (self.nextPage>self.currentPage) {
                self.pullCollectionView.refreshFooterView.isend = NO;
            }else{
                self.pullCollectionView.refreshFooterView.isend = YES;
            }
        }
        [self.pullCollectionView endRefreshing];
        [self.pullCollectionView endLoadingMore];
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        [SVProgressHUD showErrorWithStatus:STR_MSG_NETWORK_ERROR];
        [self.pullCollectionView endRefreshing];
        [self.pullCollectionView endLoadingMore];
    }];
}

- (void)showChooseView:(id)sender
{
    self.viewController.chooseView.hidden = NO;
    [self.alredaySelectArray removeAllObjects];
}

- (void)buttonSectionAllAction:(id)sender
{
    for (NSDictionary *dic in self.currentArray) {
        if ([dic ql_hasObjectForKey:@"advertisementPic"]) {
            break;
        }
        [self.alredaySelectArray setObject:@YES forKey:[NSString stringWithFormat:@"%@",dic[@"ID"]]];
        [self.pullCollectionView reloadData];
    }
}

- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section
{
  
    return self.currentArray.count;
}

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
    
    NSArray * goods = self.currentArray;
    TRMemuCell *cell =[collectionView dequeueReusableCellWithReuseIdentifier:@"TRMemuCell" forIndexPath:indexPath];
    if (goods.count>indexPath.row) {
        cell.tag=indexPath.row;
        cell.info = goods[indexPath.row];
        
        //添加长按手势,可能要处理冲突
        UILongPressGestureRecognizer * longP = [[UILongPressGestureRecognizer alloc]initWithTarget:self action:@selector(showChooseView:)];
        longP.minimumPressDuration = 1;
        
        cell.tag=indexPath.row;
        [cell addGestureRecognizer:longP];
        
       // cell.selectImageView.hidden = self.viewController.chooseView.hidden;
        if ([[self.alredaySelectArray objectForKey:[NSString stringWithFormat:@"%@",self.currentArray[indexPath.row][@"ID"]]] boolValue]) {
            [collectionView selectItemAtIndexPath:indexPath animated:NO scrollPosition:UICollectionViewScrollPositionNone];
            cell.selected=YES;
        }else{
            cell.selected = NO;
        }

    }
    return cell;
    
}

-(void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath
{
    NSArray *arr = [self currentArray];
    NSDictionary *dic = [arr objectAtIndex:indexPath.row];
    if (self.viewController.chooseView.hidden) {
        if ([dic ql_hasObjectForKey:@"advertisementPic"]) {
            NSString *url = [dic ql_stringForKey:@"url"];
            if([dic ql_hasObjectForKey:@"productId"]&&[dic ql_stringForKey:@"productId"].length>0){
                NSString *productId = [dic ql_stringForKey:@"productId"];
                [QLPlayerManager openProductDetailWithId:productId viewController:self.viewController.navigationController];
            }else if (url&&url.length>0) {
                [QLPlayerManager openBrowserWithUrl:url title:@" . " userId:dic[@"userId"] viewController:self.viewController];
            }
            
        }else{
            [QLPlayerManager openProductDetailWithId:[dic ql_stringForKey:@"ID"] viewController:self.viewController];
        }
    }else{
        if ([dic ql_hasObjectForKey:@"advertisementPic"]) {
            [self.pullCollectionView reloadData];
            return;
        }
        [self.alredaySelectArray setObject:@YES forKey:[NSString stringWithFormat:@"%@",arr[indexPath.row][@"ID"]]];
        [self.pullCollectionView reloadData];
    }
}

#pragma mark - UICollectionViewDelegateFlowLayout
- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath {
    NSArray * goods = self.currentArray;
    TRMemuCell *cell =[[TRMemuCell alloc] init];
    cell.info = [goods objectAtIndex:indexPath.row];
    //return cell.frame.size;
    CGSize size = [cell getSize];
    return [cell getSize];
}

- (CGFloat)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout minimumLineSpacingForSectionAtIndex:(NSInteger)section
{
    return 1;
}

- (CGFloat)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout minimumInteritemSpacingForSectionAtIndex:(NSInteger)section
{
    return 1;
}

#pragma mark - ad
- (void)loadAdlist
{
    AFHTTPRequestOperationManager *requestManager = [AFHTTPRequestOperationManager manager];
    requestManager.responseSerializer.acceptableContentTypes = [NSSet setWithObject:@"text/html"];
    [requestManager GET:@"http://ping.vsmu.cn/app/guanggaowei?type=2" parameters:nil success:^(AFHTTPRequestOperation *operation, id responseObject) {
        
        ApplicationDelegate.adArray = responseObject[@"contents"];
        
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        
    }];
}

#pragma mark - UIScrollViewDelegate
- (void)scrollViewWillEndDragging:(UIScrollView *)scrollView withVelocity:(CGPoint)velocity targetContentOffset:(inout CGPoint *)targetContentOffset
{
    TRFindViewController *fvc = (TRFindViewController*)self.viewController;
    if (historyY+150<targetContentOffset->y)
    {
        [fvc fullScreen];
    }
    else if(historyY-150>targetContentOffset->y)
    {
        [fvc fullScreenExit];
    }
}

- (void)scrollViewDidScroll:(UIScrollView *)scrollView{
    historyY = scrollView.contentOffset.y;
}

@end
